package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;

    /**
     * 营业额统计
     *
     * @param begin,end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //存储当前日期到结束日期
        List<LocalDate> dateList = new ArrayList<>();
        //存储数据
        List<Double> turnoverList = new ArrayList<>();
        while (true) {
            //如果开始时间等于结束时间,结束循环
            if (begin.equals(end.plusDays(1))) {
                break;
            }

            dateList.add(begin);
            //构建两个日期数据,查询数据库
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            //调用持久层方法查询数据库当前天营业额
            Double amount = reportMapper.queryTurnover(beginTime, endTime);
            amount = amount == null ? 0.0 : amount;
            //然后将开始时间加上一天
            begin = begin.plusDays(1);
            //将持久层查询出来的营业额存储起来
            turnoverList.add(amount);
        }

        return new TurnoverReportVO(StringUtils.join(dateList, ",")
                , StringUtils.join(turnoverList, ","));
    }

    /**
     * 用户数量统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //存储日期,dateList
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        //存储总数量
        List<Integer> totalUserCount = new ArrayList<>();
        //存储新用户数量
        List<Integer> newUserCount = new ArrayList<>();
        for (LocalDate date : dateList) {
            //调用持久层查询当前日期总用户和新用户数量
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalCount = reportMapper.queryTotalUser(endTime);
            Integer newCount = reportMapper.queryNewUser(beginTime, endTime);
            totalUserCount.add(totalCount);
            newUserCount.add(newCount);
        }

        return new UserReportVO(StringUtils.join(dateList, ","),
                StringUtils.join(totalUserCount, ","),
                StringUtils.join(newUserCount, ","));
    }

    /**
     * 订单数量统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //创建变量分别统计每天订单数,有效订单数,总订单数,总有效订单数,日期,完成路
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))) {
            dateList.add(begin);
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            //查询每天总订单数
            Integer countAll = reportMapper.queryAllOrder(beginTime, endTime);
            Integer countValid = reportMapper.queryValidOrder(beginTime, endTime);
            orderCountList.add(countAll);
            validOrderCountList.add(countValid);
            begin = begin.plusDays(1);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double rate = totalOrderCount != 0 ? validOrderCount.doubleValue() / totalOrderCount : 0.0;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(rate)
                .build();
    }

    /**
     * 销售排行
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10Statistics(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> list = reportMapper.queryTop(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        List<String> names = list.stream()
                .map(GoodsSalesDTO::getName)
                .collect(Collectors.toList());
        List<Integer> numbers = list.stream()
                .map(GoodsSalesDTO::getNumber)
                .collect(Collectors.toList());
        return new SalesTop10ReportVO(StringUtils.join(names,","),
                StringUtils.join(numbers,","));
    }


    /**
     * 导出运营数据
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库获取营业数据--最近30天的运营数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO data = getData(begin,end);
        //通过poi将数据写入excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);//根据模板文件创建要给新的excel文件

            XSSFSheet sheet = excel.getSheetAt(0);

            sheet.getRow(1).getCell(1).setCellValue("时间: "+ begin + "至" +end);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(data.getTurnover());
            row.getCell(4).setCellValue(data.getOrderCompletionRate());
            row.getCell(6).setCellValue(data.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(data.getValidOrderCount());
            row.getCell(4).setCellValue(data.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO perData = getData(date, date);

                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(perData.getTurnover());
                row.getCell(3).setCellValue(perData.getValidOrderCount());
                row.getCell(4).setCellValue(perData.getOrderCompletionRate());
                row.getCell(5).setCellValue(perData.getUnitPrice());
                row.getCell(6).setCellValue(perData.getNewUsers());
            }
            //通过输出流,将excel文件下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            excel.write(os);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //查询最近30天的概览数据
    public BusinessDataVO getData(LocalDate beginTime,LocalDate endTime){
        LocalDateTime begin = LocalDateTime.of(beginTime,LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(endTime,LocalTime.MAX);
        //查询当前营业额
        Double turnover = reportMapper.queryTurnover(begin, end);
        turnover = turnover == null? 0.0: turnover;
        //查询当天有效订单数
        Integer validOrderCount = reportMapper.queryValidOrder(begin, end);
        //计算平均客单价(营业额/有效订单数)
        Double unitPrice = validOrderCount == 0 ? 0.0 : (turnover.doubleValue() / validOrderCount);
        //查询当天所有订单数,用来计算订单完成率
        Integer allOrderCount = reportMapper.queryAllOrder(begin, end);
        //计算订单完成率
        Double orderCompleteRate = allOrderCount == 0 ?0.0 : (validOrderCount.doubleValue() / allOrderCount);
        //查询当前新增用户数
        Integer newUserCount = reportMapper.queryNewUser(begin, end);

        return new BusinessDataVO(turnover,validOrderCount,orderCompleteRate,unitPrice,newUserCount);
    }
}
















